package com.source.baseData.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.source.baseData.entity.SlaughterHouse;
import com.source.baseData.entity.Stalls;
import com.source.baseData.service.SlaughterHouseService;
import com.source.baseData.service.StallsService;
import com.source.labelAndBarcode.entity.LabelingRecord;
import com.source.labelAndBarcode.service.LabelingRecordService;
import com.source.labelAndBarcode.vo.SlaughterHouseVo;
import com.source.labelAndBarcode.vo.StallsVo;
import com.source.utils.CommonResult;
import com.source.utils.ExcelUtil;
import com.source.utils.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Joey
 * @since 2021-02-10
 */
@Api(tags = "档口基础数据管理")
@RestController
@CrossOrigin
@RequestMapping("/baseData/stalls")
public class StallsController {

    @Autowired
    StallsService stallsService;

    @Autowired
    LabelingRecordService recordService;

    @Autowired
    SlaughterHouseService houseService;

    @ApiOperation(value = "下载excel")
    @GetMapping(value = "/downloadExcel", produces = "application/vnd.ms-excel;charset=utf-8")
    public CommonResult<String> downloadExcel(HttpServletResponse response) throws IOException {
        List<StallsVo> allVo = stallsService.findAllOnMultiStatus(1);
        ExcelUtil.downloadExcel(response, StallsVo.class, allVo);
        return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
    }

    @ApiOperation(value = "上传Excel，存储数据到数据库中")
    @PostMapping(value = "/uploadExcel", produces = "application/json;charset=utf-8")
    public CommonResult<String> uploadExcel(@RequestPart(value = "excelFile", required = false) MultipartFile excelFile) throws IOException {
        if (null != excelFile && !excelFile.isEmpty()) {
            ExcelUtil.uploadExcel(excelFile, Stalls.class, stallsService);
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation(value = "管理员审核 ", notes = "单个审核，传id")
    @PostMapping(value = "/confirm/{id}")
    public CommonResult<String> confirm(@PathVariable String id) {
        Stalls byId = stallsService.getById(id);
        try {
            if (byId.getStatus() == 3) {
                byId.setStatus(0);
                if (stallsService.updateById(byId) && stallsService.removeById(id)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else if (byId.getStatus() == 2) {
                byId.setStatus(1);
                if (stallsService.updateById(byId)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else {
                return new CommonResult<String>(ResultEnum.ERROR, "该数据不处于待删除或待通过状态！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiOperation(value = "管理员审核（审核不通过） ", notes = "单个审核，传id，如果是待删除状态，执行后会恢复正常\n如果是待发布状态，执行后会删除数据")
    @PostMapping(value = "/disConfirm/{id}")
    public CommonResult<String> disConfirm(@PathVariable String id) {
        Stalls byId = stallsService.getById(id);
        try {
            if (byId.getStatus() == 3) {
                byId.setStatus(1);
                if (stallsService.updateById(byId)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else if (byId.getStatus() == 2) {
                byId.setStatus(0);
                if (stallsService.updateById(byId) && stallsService.removeById(id)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else {
                return new CommonResult<String>(ResultEnum.ERROR, "该数据不处于待删除或待通过状态！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }


    @ApiOperation(value = "增加一个档口", notes = "- 等待管理员审核")
    @PostMapping("/saveStall")
    public CommonResult<String> requestForSavingStall(@RequestBody @Validated Stalls stall) {
        try {
            stall.setStallsNumber(IdWorker.get32UUID());
            if (stallsService.save(stall)) {
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }
        } catch (Exception e) {
            return new CommonResult<String>(ResultEnum.ERROR);
        }

    }


    @ApiOperation("根据id删除一个数据，等待管理员审核")
    @DeleteMapping("/requestForDeletingById/{id}")
    public CommonResult<String> requestForDeletingById(@PathVariable(value = "id") String id) {
        QueryWrapper<Stalls> wrapper = new QueryWrapper<>();
        Stalls stall = stallsService.getOne(wrapper.eq("stallsId", id));
        stall.setStatus(3);
        if (stallsService.saveOrUpdate(stall)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation("根据id批量删除数据，等待管理员审核")
    @DeleteMapping("/requestForDeletingByIds/{ids}")
    public CommonResult<String> requestForDeletingByIds(@PathVariable(value = "ids") List<String> ids) {
        QueryWrapper<Stalls> wrapper = new QueryWrapper<>();
        wrapper.in("stallsId", ids);
        List<Stalls> stalls = stallsService.list(wrapper);
        for (Stalls stall : stalls) {
            stall.setStatus(3);
        }
        if (stallsService.saveOrUpdateBatch(stalls)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @Deprecated
    @ApiOperation("管理员批量审核待删除数据")
    @DeleteMapping("/permissionForDeletingByIds/{ids}")
    public CommonResult<String> permissionForDeletingByIds(@PathVariable(value = "ids") List<String> ids) {
        QueryWrapper<Stalls> wrapper = new QueryWrapper<>();
        wrapper.in("stallsId", ids);
        List<Stalls> stalls = stallsService.list(wrapper);
        for (Stalls stall : stalls) {
            stall.setStatus(0);
        }

        if (stallsService.saveOrUpdateBatch(stalls) && stallsService.removeByIds(ids)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation("根据id修改数据，主键id不可修改")
    @PutMapping("/updateById")
    public CommonResult<String> updateById(@RequestBody Stalls stall) {
        if (stallsService.updateById(stall)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation(value = "查询所有档口数据")
    @GetMapping("/findAll")
    public CommonResult<List<StallsVo>> findAll() {
        List<StallsVo> list = stallsService.findAll();
        return new CommonResult<List<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation(value = "分页查询所有档口数据")
    @GetMapping("/findAllOnPagination")
    public CommonResult<IPage<StallsVo>> findAllOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                             @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> pages = stallsService.findAllOnPagination(page);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS, pages);
    }

    @ApiOperation(value = "查询所有已通过审核的数据")
    @GetMapping("/findAllOnPermission")
    public CommonResult<List<StallsVo>> findAllOnPermission() {
        List<StallsVo> list = stallsService.findAllOnMultiStatus(1);
        return new CommonResult<List<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @GetMapping("/findAllOnPaginationAndPermission")
    @ApiOperation(value = "分页查询已通过审核的数据")
    public CommonResult<IPage<StallsVo>> findAllOnPaginationAndPermission(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                          @RequestParam(value = "size", defaultValue = "10") Integer size) {

        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> stallsPage = stallsService.findAllOnMultiStatusAndPagination(page, 1);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), stallsPage);
    }

    @ApiOperation("根据ID查询任意状态的数据（用于编辑/修改）")
    @GetMapping("/findById/{id}")
    public CommonResult<Stalls> findById(@PathVariable String id) {
        Stalls stall = stallsService.getById(id);
        return new CommonResult<Stalls>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), stall);
    }

    @ApiOperation("根据ID查询任意状态的数据（用于明细）")
    @GetMapping("/findVoById/{id}")
    public CommonResult<StallsVo> findVoById(@PathVariable String id) {
        StallsVo byId = stallsService.findById(id);
        return new CommonResult<StallsVo>(ResultEnum.SUCCESS, byId);
    }

    @ApiOperation("根据名称模糊查询通过审核的数据")
    @GetMapping("/findByKeyWord")
    public CommonResult<List<StallsVo>> findByKeyWord(@RequestParam(value = "keyWord", required = false) String keyWord) {
        if (null == keyWord) {
            return findAllOnPermission();
        }
        List<StallsVo> list = stallsService.findByLikeName(keyWord);
        return new CommonResult<List<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation("分页多条件模糊查询通过审核的数据")
    @GetMapping("/findByRequireOnPagination")
    public CommonResult<IPage<StallsVo>> findByRequireOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                   @RequestParam(value = "size", defaultValue = "10") Integer size,
                                                                   @RequestParam(value = "keyWord", required = false) String keyWord) {
        if (null == keyWord) {
            return findAllOnPaginationAndPermission(current, size);
        }
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> list = stallsService.findByLikeNameOnPagination(page, keyWord);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @GetMapping("/findByUnChecked")
    @ApiOperation(value = "查询待审核的数据", notes = "分页")
    public CommonResult<IPage<StallsVo>> findByUnChecked(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                         @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> stallsVoIPage = stallsService.findByUnChecked(page);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS, stallsVoIPage);
    }

    @GetMapping("/findByUnCheckedAndKeyWord")
    @ApiOperation(value = "模糊查询待审核的数据", notes = "分页")
    public CommonResult<IPage<StallsVo>> findByUnCheckedAndKeyWord(@RequestParam(value = "keyWord", required = false) String keyWord,
                                                                   @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                   @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (null == keyWord) {
            return findByUnChecked(current, size);
        }
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> stallsVoIPage = stallsService.findByUnCheckedAndKeyWord(keyWord, page);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS, stallsVoIPage);
    }


    @Deprecated
    @ApiOperation("查询待审核通过发布的数据")
    @GetMapping("/findAllOnPermissionAudit")
    public CommonResult<List<StallsVo>> findByPermissionAudit() {
        List<StallsVo> list = stallsService.findAllOnMultiStatus(2);
        return new CommonResult<List<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation(value = "查询待审核通过发布的数据", notes = "分页")
    @GetMapping("/findAllOnPermissionAuditAndPagination")
    public CommonResult<IPage<StallsVo>> findByPermissionAuditAndPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> list = stallsService.findAllOnMultiStatusAndPagination(page, 2);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @ApiOperation("查询待审核通过删除的数据")
    @GetMapping("/findAllOnDeletionAudit")
    public CommonResult<List<StallsVo>> findAllOnDeletionAudit() {
        List<StallsVo> list = stallsService.findAllOnMultiStatus(3);
        return new CommonResult<List<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @ApiOperation(value = "查询待审核通过删除的数据", notes = "分页")
    @GetMapping("/findAllOnDeletionAuditAndPagination")
    public CommonResult<IPage<StallsVo>> findAllOnDeletionAuditAndPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                             @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> list = stallsService.findAllOnMultiStatusAndPagination(page, 3);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @ApiOperation(value = "管理员审核 - 发布通过 ", notes = "- 批量审核：参数传递id的字符串 用英文的逗号分开")
    @PostMapping(value = "/permissionForPublish/{ids}")
    public CommonResult<String> permissionForPublish(@PathVariable("ids") List<String> ids) {
        QueryWrapper<Stalls> wrapper = new QueryWrapper<Stalls>();
        List<Stalls> stalls = stallsService.list(wrapper.in("stallsId", ids));

        for (Stalls stall : stalls) {
            stall.setStatus(1);
        }

        if (stallsService.saveOrUpdateBatch(stalls)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation(value = "根据用户id查询档口", notes = "分页")
    @GetMapping("/findByUserId/{userId}")
    public CommonResult<IPage<StallsVo>> findByUserIdOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                  @RequestParam(value = "size", defaultValue = "10") Integer size,
                                                                  @PathVariable String userId) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> list = stallsService.findByUserIdOnPagination(page, userId);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation(value = "根据屠宰场id查询档口", notes = "分页")
    @GetMapping("/findBySlaughterHouseId/{slaughterHouseId}")
    public CommonResult<IPage<StallsVo>> findBySlaughterHouseIdOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                            @RequestParam(value = "size", defaultValue = "10") Integer size,
                                                                            @PathVariable String slaughterHouseId) {
        Page<StallsVo> page = new Page<>(current, size);
        IPage<StallsVo> list = stallsService.findBySlaughterHouseIdOnPagination(page, slaughterHouseId);
        return new CommonResult<IPage<StallsVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation(value = "某档口使用标签数 - 当天")
    @GetMapping("/dailyRecord")
    public CommonResult<Integer> dailyRecord(Integer id) {

        QueryWrapper<LabelingRecord> wrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        wrapper.eq("stallsId", id).like("labelingDate", format);
        int count = recordService.count(wrapper);
        return new CommonResult<Integer>(ResultEnum.SUCCESS, count);
    }

    @ApiOperation(value = "某档口使用标签数 - 当周")
    @GetMapping("/weeklyRecord")
    public CommonResult<Integer> weeklyRecord(Integer id) {
        int count = recordService.weeklyRecord(id);
        return new CommonResult<Integer>(ResultEnum.SUCCESS, count);
    }

    @ApiOperation(value = "某档口使用标签数 - 当月")
    @GetMapping("/monthlyRecord")
    public CommonResult<Integer> monthlyRecord(Integer id) {
        int count = recordService.monthlyRecord(id);
        return new CommonResult<Integer>(ResultEnum.SUCCESS, count);
    }

    @ApiOperation(value = "某档口使用标签数 - 当天 + 按父禽类统计")
    @GetMapping("/dailyRecordByPoultry")
    public CommonResult<List<Map<String, BigInteger>>> dailyRecordByPoultry(Integer id) {
        List<Map<String, BigInteger>> recordByPoultry = recordService.dailyRecordByPoultry(id);
        return new CommonResult<List<Map<String, BigInteger>>>(ResultEnum.SUCCESS, recordByPoultry);
    }

    @ApiOperation(value = "某档口使用标签数 - 当周 + 按父禽类统计")
    @GetMapping("/weeklyRecordByPoultry")
    public CommonResult<List<Map<String, BigInteger>>> weeklyRecordByPoultry(Integer id) {
        List<Map<String, BigInteger>> recordByPoultry = recordService.weeklyRecordByPoultry(id);
        return new CommonResult<List<Map<String, BigInteger>>>(ResultEnum.SUCCESS, recordByPoultry);
    }

    @ApiOperation(value = "某档口使用标签数 - 当月 + 按父禽类统计")
    @GetMapping("/monthlyRecordByPoultry")
    public CommonResult<List<Map<String, BigInteger>>> monthlyRecordByPoultry(Integer id) {
        List<Map<String, BigInteger>> recordByPoultry = recordService.monthlyRecordByPoultry(id);
        return new CommonResult<List<Map<String, BigInteger>>>(ResultEnum.SUCCESS, recordByPoultry);
    }

    @ApiOperation(value = "某档口使用标签数 - 当天 + 按去向市场 + 按父禽类统计 + 降序")
    @GetMapping("/dailyRecordByPoultryAndToMark")
    public CommonResult<List<Map<Object, Object>>> dailyRecordByPoultryAndToMark(Integer id) {
        List<Map<Object, Object>> recordByPoultry = recordService.dailyRecordByPoultryAndToMark(id);
        return new CommonResult<List<Map<Object, Object>>>(ResultEnum.SUCCESS, recordByPoultry);
    }

    @ApiOperation(value = "某档口使用标签数 - 当周 + 按去向市场 + 按父禽类统计 + 降序")
    @GetMapping("/weeklyRecordByPoultryAndToMark")
    public CommonResult<List<Map<Object, Object>>> weeklyRecordByPoultryAndToMark(Integer id) {
        List<Map<Object, Object>> recordByPoultry = recordService.weeklyRecordByPoultryAndToMark(id);
        return new CommonResult<List<Map<Object, Object>>>(ResultEnum.SUCCESS, recordByPoultry);
    }

    @ApiOperation(value = "某档口使用标签数 - 当月 + 按去向市场 + 按父禽类统计 + 降序")
    @GetMapping("/monthlyRecordByPoultryAndToMark")
    public CommonResult<List<Map<Object, Object>>> monthlyRecordByPoultryAndToMark(Integer id) {
        List<Map<Object, Object>> recordByPoultry = recordService.monthlyRecordByPoultryAndToMark(id);
        return new CommonResult<List<Map<Object, Object>>>(ResultEnum.SUCCESS, recordByPoultry);
    }


    @ApiOperation(value = "查询所有屠宰场")
    @GetMapping("/findAllSH")
    public CommonResult<List<SlaughterHouseVo>> findAllSH() {
        List<SlaughterHouseVo> list = houseService.findAllOnPermission();
        return new CommonResult<List<SlaughterHouseVo>>(ResultEnum.SUCCESS, list);
    }
}

